package com.bifrost.listener;

import com.bifrost.constant.RefundStatus;
import com.bifrost.entity.OrderReturn;
import com.bifrost.entity.TransactionSendLog;
import com.bifrost.event.TransactionEvent;
import com.bifrost.repository.OrderReturnRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 退款状态监听
 * @author wqhe
 * @date 2018/12/17/11:06
 */
@Component
@Async
public class RefundStatusListener implements ApplicationListener<TransactionEvent> {

    private static final Logger LOGGER = LoggerFactory.getLogger(RefundStatusListener.class);

    @Autowired
    OrderReturnRepository orderReturnRepository;

    @Override
    public void onApplicationEvent(TransactionEvent transactionEvent) {
        try {
            Object source = transactionEvent.getSource();
            //退单退款完成修改退款状态
            if (source instanceof OrderReturn && TransactionSendLog.Type.REFUND.equals(transactionEvent.getType())) {
                OrderReturn orderReturn = (OrderReturn) source;
                LOGGER.info(String.format("退单：%s，退款成功，修改退单状态为已退款",orderReturn.getReturnNumber()));
                orderReturn.setRefundStatus(RefundStatus.REFUNDED);
                orderReturnRepository.save(orderReturn);
            }
        } catch (Exception e) {
            LOGGER.error("退款状态修改失败：",e);
        }
    }
}
